﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace QuanLyKhachHang.Forms
{
    #region using
    using QuanLyKhachHang.BUS;
    using QuanLyKhachHang.DTO;
    using QuanLyKhachHang.Utilities;
    #endregion

    public partial class frmTongHop : Form
    {
        private delegate void TimeTask();
        private frmWaiting waiting;
        private DataSet objDonViDS;
        private DataTable dataTable = new DataTable();
        private string maDonVi;
        private int thang;
        private int nam;

        public frmTongHop()
        {
            InitializeComponent();
            InitGridViewHienThi();
        }

        public void InitGridViewHienThi()
        {
            string str = "";
            long i = 0;
            DataColumn col1 = new DataColumn("STT", str.GetType());
            DataColumn col2 = new DataColumn("TENKH", str.GetType());
            DataColumn col3 = new DataColumn("DIACHI", str.GetType());

            DataColumn col4 = new DataColumn("BPTN", str.GetType());
            DataColumn col5 = new DataColumn("BKTN", str.GetType());
            DataColumn col6 = new DataColumn("EMSTN", str.GetType());
            DataColumn col7 = new DataColumn("EMSNN", str.GetType());
            DataColumn col8 = new DataColumn("VE", str.GetType());
            DataColumn col9 = new DataColumn("BCUT", str.GetType());
            DataColumn col10 = new DataColumn("TG", str.GetType());
            DataColumn col11 = new DataColumn("TM", str.GetType());
            DataColumn col12 = new DataColumn("TBT", str.GetType());
            
            DataColumn col13 = new DataColumn("MAKH", str.GetType());
            DataColumn col14 = new DataColumn("TONGDOANHTHU", str.GetType());

            dataTable.Columns.Add(col1);
            dataTable.Columns.Add(col2);
            dataTable.Columns.Add(col3);
            dataTable.Columns.Add(col4);
            dataTable.Columns.Add(col5);
            dataTable.Columns.Add(col6);
            dataTable.Columns.Add(col7);
            dataTable.Columns.Add(col8);
            dataTable.Columns.Add(col9);
            dataTable.Columns.Add(col10);
            dataTable.Columns.Add(col11);
            dataTable.Columns.Add(col12);
            dataTable.Columns.Add(col13);
            dataTable.Columns.Add(col14);
        }


        public void LoadDonVi()
        {
            var objBUS = new DonViBUS(GlobalVariables.g_strConnectionString);

            try
            {
                var objDS = objBUS.SelectAll();

                for (int i = 0; i < objDS.Tables["DonVi"].Rows.Count; i++)
                {
                    DataRow row = objDS.Tables["DonVi"].Rows[i];
                    cbxDonVi.Items.Add(new DonViDTO { MADONVI = row["MADONVI"].ToString(), TENDONVI = row["TENDONVI"].ToString() });
                }

                if (cbxDonVi.Items.Count > 0)
                    cbxDonVi.SelectedIndex = 0;
            }
            catch (System.Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        public bool ValidateInput()
        {
            if (cbxDonVi.Text.Equals(""))
            {
                MessageBox.Show("Bạn chưa chọn đơn vị", "Bao Loi",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return false;
            }

            if (txtThang.Text.Equals(""))
            {
                MessageBox.Show("Bạn chưa nhập tháng", "Bao Loi",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return false;
            }

            if (txtNam.Text.Equals(""))
            {
                MessageBox.Show("Bạn chưa nhập năm", "Bao Loi",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return false;
            }

            if (!Utils.IsNumeric(txtThang.Text))
            {
                MessageBox.Show("Tháng phải là số hợp lệ", "Bao Loi",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return false;
            }
            else
            {
                if (int.Parse(txtThang.Text) < 1 || int.Parse(txtThang.Text) > 12)
                {
                    MessageBox.Show("Tháng phải từ 1-12 ", "Bao Loi",
                        MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return false;
                }
            }

            if (!Utils.IsNumeric(txtNam.Text))
            {
                MessageBox.Show("Năm phải là số hợp lệ", "Bao Loi",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return false;
            }
            else
            {
                if (int.Parse(txtNam.Text) <= 0)
                {
                    MessageBox.Show("Năm phải từ > 0 ", "Bao Loi",
                        MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return false;
                }
            }

            return true;
        }

        public bool HaveDataInRow(DataTable _tbl, int index)
        {
            try
            {
                DataRow row = _tbl.Rows[index];
                return true;
            }
            catch
            {
                return false;
            }
        }

        public DataRow GetRowForTongDoanhThuMax(DataTable tbl, ref int index)
        {
            index = 0;
            long tongtienmax = long.Parse(tbl.Rows[0]["TONGDOANHTHU"].ToString());
            DataRow row;
            for (int i = 1; i < tbl.Rows.Count; i++)
            {
                if (long.Parse(tbl.Rows[i]["TONGDOANHTHU"].ToString()) > tongtienmax)
                {
                    tongtienmax = long.Parse(tbl.Rows[i]["TONGDOANHTHU"].ToString());
                    index = i;
                }
            }
            row = tbl.Rows[index];
            return row;
        }

        private void btnXem_Click(object sender, EventArgs e)
        {
            if (ValidateInput())
            {
                dataTable.Clear();
                dtgvDanhSachHienThi.DataSource = null;
                dtgvDanhSachHienThi.Columns.Clear();

                var objBUS = new TongHopBUS(GlobalVariables.g_strConnectionString);
                var objDS = objBUS.SelectByMADONVI(((DonViDTO)cbxDonVi.SelectedItem).MADONVI, int.Parse(txtThang.Text), int.Parse(txtNam.Text));

                if (objDS.Tables[0].Rows.Count > 0)
                {
                    int currentIndex = 0; 
                    for (int i = 0; i < objDS.Tables[0].Rows.Count; i++) 
                    { 
                        bool contains = false; 

                        for(int j = 0; j <= currentIndex; j++) 
                        {
                            if (HaveDataInRow(dataTable, j))
                            {
                                if (objDS.Tables[0].Rows[i]["MAKH"].ToString() == (dataTable.Rows[j]["MAKH"].ToString()))
                                {
                                    contains = true;
                                    break;
                                }
                            }
                        } 

                        if(!contains) 
                        { 
                            DataRow row2;
                            dataTable.Rows.Add();
                            row2 = dataTable.Rows[currentIndex];

                            row2["STT"] = (currentIndex + 1).ToString();
                            row2["MAKH"] = objDS.Tables[0].Rows[i]["MAKH"].ToString();
                            row2["TENKH"] = objDS.Tables[0].Rows[i]["TENKH"].ToString();
                            row2["DIACHI"] = objDS.Tables[0].Rows[i]["DIACHI"].ToString();

                            currentIndex++;
                        } 
                    }

                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        int count = 0;
                        long tongtien = 0;
                        int indexCol = 0;
                        for (int j = 0; j < objDS.Tables[0].Rows.Count; j++)
                        {
                            if (dataTable.Rows[i]["MAKH"].ToString() == objDS.Tables[0].Rows[j]["MAKH"].ToString())
                            {
                                dataTable.Rows[i][indexCol + 3] = objDS.Tables[0].Rows[j]["SOTIEN"];
                                tongtien += long.Parse(objDS.Tables[0].Rows[j]["SOTIEN"].ToString());
                                count++;
                                indexCol++;
                                if (count == 9)
                                {
                                    dataTable.Rows[i]["TONGDOANHTHU"] = tongtien.ToString();
                                    count = 0;
                                    break;
                                }
                            }
                        }
                        
                    }

                    if (dataTable.Rows.Count > 1)
                    {
                        DataTable newTbl = dataTable.Clone();
                        newTbl.Clear();
                        for (int i = 0; i < dataTable.Rows.Count; i++)
                        {
                            int index = 0;
                            DataRow row = GetRowForTongDoanhThuMax(dataTable, ref index);
                            DataRow newRow = newTbl.NewRow();
                            newRow.ItemArray = (object[])row.ItemArray.Clone();

                            dataTable.Rows.Remove(row);
                            newTbl.Rows.Add(newRow);
                            
                            if (dataTable.Rows.Count == 0)
                                break;
                            i = i - 1;
                        }

                        dataTable = newTbl;
                    }

                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        dataTable.Rows[i]["TONGDOANHTHU"] = string.Format("{0:#,##0;Nothing}", long.Parse(dataTable.Rows[i]["TONGDOANHTHU"].ToString())); 
                    }

                    DataView objTimeSheetDV = new System.Data.DataView(dataTable);
                    objTimeSheetDV.AllowNew = false;
                    dtgvDanhSachHienThi.AutoGenerateColumns = false;
                    dtgvDanhSachHienThi.DataSource = objTimeSheetDV;

                    DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
                    {
                        HeaderText = "STT",
                        DataPropertyName = "STT",
                        Name = "STT",
                        Width = 30
                    };
                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "MAKH",
                        Name = "MAKH",
                        Visible = false
                    };
                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        HeaderText = "Tên KH",
                        DataPropertyName = "TENKH",
                        Name = "TENKH",
                        Width = 250
                    };
                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        HeaderText = "Địa chỉ",
                        DataPropertyName = "DIACHI",
                        Name = "DIACHI",
                        Width = 250
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "BPTN",
                        Name = "BPTN",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "BKTN",
                        Name = "BKTN",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "EMSTN",
                        Name = "EMSTN",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "EMSNN",
                        Name = "EMSNN",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "VE",
                        Name = "VE",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "BCUT",
                        Name = "BCUT",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "TG",
                        Name = "TG",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "TM",
                        Name = "TM",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "TBT",
                        Name = "TBT",
                        Visible = false
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    objColumn = new DataGridViewTextBoxColumn
                    {
                        HeaderText = "Tổng doanh thu",
                        DataPropertyName = "TONGDOANHTHU",
                        Name = "TONGDOANHTHU",
                        Width = 160
                    };

                    dtgvDanhSachHienThi.Columns.Add(objColumn);

                    dtgvDanhSachHienThi.ClearSelection();
                }
            }
        }

        private void frmTongHop_Load(object sender, EventArgs e)
        {
            LoadDonVi();
        }

        private void dtgvDanhSachHienThi_Click(object sender, EventArgs e)
        {
            try
            {
                txtTenKH.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["TENKH"].Value.ToString();
                txtDiaChi.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["DIACHI"].Value.ToString();
                txtBPTN.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["BPTN"].Value.ToString();
                txtBKTN.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["BKTN"].Value.ToString();
                txtVExpress.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["VE"].Value.ToString();
                txtEMSTN.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["EMSTN"].Value.ToString();
                txtEMSNN.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["EMSNN"].Value.ToString();
                txtBCUT.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["BCUT"].Value.ToString();
                txtTemGiay.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["TG"].Value.ToString();
                txtTemMay.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["TM"].Value.ToString();
                txtTheBuuThiep.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["TBT"].Value.ToString();
                txtTongDoanhThu.Text = dtgvDanhSachHienThi.SelectedRows[0].Cells["TONGDOANHTHU"].Value.ToString();
            }
            catch
            {
            }
        }
    }
}
